<?php

/**
 * 数据表 "{{member}}"的模型类.
 *
 * The followings are the available columns in table '{{member}}':
 * @property integer $zm_id
 * @property string $zm_name
 * @property string $zm_psword
 * @property string $zm_paypsword
 * @property string $zm_email
 * @property string $zm_mob
 * @property integer $zm_value
 * @property integer $zm_credit
 * @property integer $zm_upcredit
 * @property double $zm_balance
 * @property string $zm_face
 * @property integer $zmt_id
 * @property integer $zmg_id
 * @property integer $zm_last_time
 * @property string $zm_ip
 * @property integer $zm_svr_startdt
 * @property integer $zm_svr_enddt
 * @property integer $zm_check_status
 * @property string $zm_code
 * @property string $zm_questio
 * @property string $zm_answer
 * @property string $zm_reg_ip
 * @property integer $zm_today_time
 * @property integer $zm_total_time
 * @property integer $zm_status
 * @property integer $inputtime
 * @property integer $updatetime
 */
class Member extends CActiveRecord
{
	//定义变量，记住此次登录
	public $rememberMe;
	//定义变量。存放验证码	
	public $verifyCode;

	//重复密码
	public $re_psword;
	//重复支付密码
	public $re_paypsword;
	//旧密码
	public $old_psword;
	//重复支付密码
	public $old_paypsword;
	//表单验证串，防止非法提交
	public $formHash;
	//会员等级
	public $level;
	//会员等级
	public $group;
	//查询排序 1创建时间倒序，2销费额倒序
	public $list_order=1;
	
	public $captcha;
	/**
	 * 返回基于自身的AR实例
	 * @param string $className 类名
	 * @return Member 实例
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string 返回表名
	 */
	public function tableName()
	{
		return '{{member}}';
	}

	/**
	 * @return array 模型验证规则.
	 */
	public function rules()
	{
		return array(
// 			array('zm_balance', 'numerical'),
// 			array('zm_name, zm_ip, zm_reg_ip', 'length', 'max'=>25),
// 			array('zm_psword, zm_paypsword, zm_face', 'length', 'max'=>100),
// 			array('zm_email', 'length', 'max'=>255),
// 			array('zm_mob', 'length', 'max'=>11),
// 			array('zm_question, zm_answer', 'length', 'max'=>50),
// 			array('zm_face',
// 					'file',
// 					'allowEmpty'=>true,
// 					'types'=>'jpg,gif,png',
// 					'maxSize'=>1024 * 1024 * 1,
// 					'tooLarge'=>'头像最大不超过1MB，请重新上传!',
// 			),
		array('zm_name', 'length' ,'min'=>3, 'max'=>20),
		array('zm_psword', 'length' ,'min'=>6, 'max'=>36),
		array('zm_id, zm_name, zm_psword, zm_paypsword, zm_email,level, zm_mob, zm_value, zm_credit, list_order, zm_upcredit, zm_balance, zm_face, zmt_id, zmg_id, zm_last_time, zm_ip, zm_svr_startdt, zm_svr_enddt, zm_check_status, zm_code, zm_question, zm_answer, zm_reg_ip, zm_today_time, zm_total_time, zm_status, inputtime, updatetime', 'safe', 'on'=>'search'),
		array('zm_psword, zm_email, old_psword, re_psword, captcha, old_paypsword, zm_paypsword, re_paypsword, zm_email', 'required', 'on'=>'forgot'),
		array('re_psword,verifyCode,zm_email', 'required','on'=>'register'),
		array('re_psword', 'compare','compareAttribute'=>'zm_psword','message'=> t('Confirm Password Error'),'on'=>'register'),	
		array('re_psword', 'compare','compareAttribute'=>'zm_psword','message'=>t('Confirm Password Error'),'on'=>'forgot'),
		array('re_paypsword', 'compare','compareAttribute'=>'zm_paypsword','message'=>t('Confirm Password Error'),'on'=>'forgot'),				
		array('zm_name', 'unique'),
		array('zm_email', 'length', 'max'=>255,'on'=>'registertwo'),
		array('zm_email', 'email'),
		array('zm_name', 'unique','caseSensitive'=>false,'className'=>'Member','message'=>'用户名"{value}"已经被注册，请更换'),
		array('zm_email', 'unique','caseSensitive'=>false,'className'=>'Member','message'=>'邮箱"{value}"已经被使用，请更换','on'=>'register'),
		array('zm_name', 'ext.validators.userNameCheck' ,'on'=>'register'),
		array('zm_psword', 'ext.validators.passwordCheck' ,'on'=>'register'),
		array('verifyCode', 'captcha','on'=>'register'),
		array('verifyCode', 'captcha','on'=>'getpass'),
		);
	}

	/**
	 * @return array 关联规则.
	 */
	public function relations()
	{
        return array(
            //'more'=>array(self::HAS_ONE, 'MemPro', 'zm_id'),
           // 'memtype'=>array(self::MANY_MANY, 'MemType','zd_mem_glog(zm_id=>userid,itemname=>zmt_id)'),//会员等级
        	'level_log'=>array(self::HAS_MANY, 'MemGlog', array('userid'=>'zm_id')),
            'more'=>array(self::HAS_ONE, 'MemPro', 'zm_id'),
        	'buyamount'=>array(self::STAT, 'Order', 'zm_id' , 'condition'=>'zo_status=3','select'=>'SUM(zo_amount)'),//消费总金额
        	'buyorders'=>array(self::STAT, 'Order', 'zm_id' , 'condition'=>'zo_status=3','select'=>'count(*)'),//成交订单数
            //'group'=>array(self::MANY_MANY, 'MemGroup','zd_mem_glog(array("zm_id"=>"userid"), zmg_id)'),
            //'glog'=>array(self::BELONGS_TO, 'MemType','zmt_id'),
        );
    }
	
	/**
	 * @return array 定制字段的显示标签 (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'zm_id' => '会员ID',
			'zm_name' => '用户名',
			'zm_psword' => '密码',
			'old_psword' => '旧密码',
			're_psword' => '重复密码',
			'zm_paypsword' => '支付密码',
			'zm_email' => '邮箱',
			'zm_mob' => '手机',
			'zm_value' => '积分',
			'zm_credit' => '信用指数',
			'zm_upcredit' => '提升指数',
			'zm_balance' => '余额',
			'zm_face' => '头像',
			//'zmt_id' => '等级',
			'zmg_id' => '用户组',
			'zm_last_time' => '最后登录时间',
			'zm_ip' => '最后登录',
			'zm_svr_startdt' => '服务开始时间',
			'zm_svr_enddt' => '服务结束时间',
			'zm_check_status' => '验证状态',
			'zm_code' => '识别码',
			'zm_question' => '问题',
			'zm_answer' => '答案',
			'zm_reg_ip' => '注册IP',
			'zm_today_time' => '今天登录次数',
			'zm_total_time' => '总登录次数',
			'zm_status' => '审核状态',
			'inputtime' => '创建时间',
			'updatetime' => '更新时间',
			'rememberMe'=>'记住用户名/密码',
			'verifyCode'=>'验证码',
			'captcha' =>'邮件验证码',
			'old_paypsword' =>'旧支付密码',
			're_paypsword' =>'重复新密码',
			'buyamount'=> '消费总金额',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search($pageSize=10)
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('zm_id',$this->zm_id);
		$criteria->compare('zm_name',$this->zm_name,true);
		$criteria->compare('zm_psword',$this->zm_psword,true);
		$criteria->compare('zm_paypsword',$this->zm_paypsword,true);
		$criteria->compare('zm_email',$this->zm_email,true);
		$criteria->compare('zm_mob',$this->zm_mob,true);
		$criteria->compare('zm_value',$this->zm_value);
		$criteria->compare('zm_credit',$this->zm_credit);
		$criteria->compare('zm_upcredit',$this->zm_upcredit);
		$criteria->compare('zm_balance',$this->zm_balance);
		$criteria->compare('zm_face',$this->zm_face,true);		
		$criteria->compare('zm_last_time',$this->zm_last_time);
		$criteria->compare('zm_ip',$this->zm_ip,true);
		$criteria->compare('zm_svr_startdt',$this->zm_svr_startdt);
		$criteria->compare('zm_svr_enddt',$this->zm_svr_enddt);
		$criteria->compare('zm_check_status',$this->zm_check_status);
		$criteria->compare('zm_code',$this->zm_code,true);
		$criteria->compare('zm_question',$this->zm_question,true);
		$criteria->compare('zm_answer',$this->zm_answer,true);
		$criteria->compare('zm_reg_ip',$this->zm_reg_ip,true);
		$criteria->compare('zm_today_time',$this->zm_today_time);
		$criteria->compare('zm_total_time',$this->zm_total_time);
		$criteria->compare('zm_status',$this->zm_status);
		$criteria->compare('inputtime',$this->inputtime);
		$criteria->compare('updatetime',$this->updatetime);
		
		$criteria->join = '';

		//根据会员等级查询
		if(!empty($this->level)){
			$criteria->join .= ' LEFT JOIN {{mem_glog}} memlog ON memlog.userid=t.zm_id ';
			$criteria->addCondition(' memlog.itemname ='.$this->level);
		}else{
			//根据会员组查询
			if(!empty($this->zmg_id)){
				$criteria->join .= ' LEFT JOIN {{mem_glog}} memlog ON memlog.userid=t.zm_id ';
				$criteria->join .= ' LEFT JOIN {{mem_type}} memtype ON memlog.itemname=memtype.zmt_id ';
				$criteria->addCondition(' memtype.zmg_id ='.$this->zmg_id);
			};
		}
		//查询排序
		if($this->list_order==1){
			//创建时间倒序
			$criteria->order = " inputtime DESC ";
		}elseif($this->list_order==2){
			//销费额倒序
			$criteria->join .= " LEFT JOIN {{order}} o ON o.zm_id=t.zm_id";
			$criteria->select =  " t.*,SUM( o.zo_amount) as nums ";
			$criteria->addCondition(' o.zo_status=3 ');
			$criteria->group =  " t.zm_id ";
			$criteria->order = " nums DESC ";
		}elseif($this->list_order==3){
			//购买量倒序
			$criteria->join .= " LEFT JOIN {{order}} o ON o.zm_id=t.zm_id";
			$criteria->join .= " LEFT JOIN {{ord_product}} od ON o.zo_id=od.zo_id";
			$criteria->select =  " t.*,SUM( od.zop_nums) as nums ";
			$criteria->group =  " t.zm_id ";
			$criteria->order = " nums DESC ";
		}
		
		$criteria->order = " inputtime DESC ";//默认为时间倒序
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'pagination'=>array('pageSize'=>$pageSize),
		));
	}

	/*
	*@密码验证
	*@param $password 密码串
	*@param $type 加密类型 1.登录密码 2.支付密码
	*/
	public function checkPassword( $password , $type=1 ){
		if( $type == 1 ){
			return md5( md5( $password ).$this->code ) === $this->zm_psword;
		}else{
			return md5( md5( $password.$this->code ).$this->code ) === $this->zm_paypsword;
		}
	}

	/*
	*@密码加密
	*@param $password 密码串
	*@param $type 加密类型 1.登录密码 2.支付密码
	*/
	public function passwordEncode( $password , $type=1 ){
		if( $type == 1 ){
			return md5( md5( $password ).$this->code );
		}else{
			return md5( md5( $password.$this->code ).$this->code );
		}
	}

	//重写__get()
	public function __get ($name){
		if($name == 'code'){
			if($this->zm_code){
				return $this->zm_code;
			}
			if(isset($_POST['LoginForm'])){
				$username = $_POST['LoginForm']['zm_name'];
			}else{
				$username = -1;
			}
			$record = Member::model()->findByAttributes(array('zm_name'=>$username)); 
			//print_r($record);exit;
			
			$zm_code = is_object($record)?$record->zm_code:'';
			if(!$zm_code){
				$zm_code = $this->createCode();
			}
			$this->zm_code = $zm_code;
			return $this->zm_code;
		}else{
			return parent::__get($name);
		}
	}
	
	//生成用户识别码
	public function createCode(){
		return create_randomstr();
	}
	
	/*
	*@持久化用户信息，登录时用,调用信息方法：Yii::app()->user->username;
	*@param $username 用户名
	*根据需要适当增加，包括关联的等级及用户组等
	*已经增加附表关联信息到$record中，附表实例访问方式：$record->more
	*/
	public function setUserInfo($username='')
	{
		if(Yii::app()->user->isGuest){
			throw new Exception('用户未登录！');
		}
		$username = $username? $username : $this->zm_name;
		$record = Member::model()->with('more'/*,'group','type'*/)->findByAttributes(array('zm_name'=>$username));
		//print_r($record);exit;
		Yii::app()->user->setState('userid',$record->zm_id,1);
		Yii::app()->user->setState('face',$record->zm_face,1);
		Yii::app()->user->setState('username',$record->zm_name,1);
		Yii::app()->user->setState('email',$record->zm_email,1);
		Yii::app()->user->setState('last_login_time',$record->zm_last_time,1);
		Yii::app()->user->setState('points',$record->zm_value,1);
		Yii::app()->user->setState('upcredit',empty($record->zm_upcredit)?'0':$record->zm_upcredit,1);
		//附表数据
		if( isset($record->more) && $record->more !== null){
			Yii::app()->user->setState('nickname',$record->more->zmp_nickname,1);
		}
		//买家会员组、
			$criteria=new CDbCriteria;
			$criteria->compare('zmg_id',1);
			$criteria->join = ' LEFT JOIN {{mem_glog}} mg ON mg.itemname=t.zmt_id ';
			$criteria->addCondition(' mg.userid ="'.$record->zm_id.'" ');
			$memberGroup = MemType::model()->find($criteria);
			$mGroup['group'] = $memberGroup->memgroup->attributes;
			$mGroup['type'] = $memberGroup->attributes;
			Yii::app()->user->setState('memgroup',$mGroup,1);
		//商家会员组
			$criteria=new CDbCriteria;
			$criteria->compare('zmg_id',3);
			$criteria->join = ' LEFT JOIN {{mem_glog}} mg ON mg.itemname=t.zmt_id ';
			$criteria->addCondition(' mg.userid ="'.$record->zm_id.'" ');
			$companyGroup = MemType::model()->find($criteria);
			if(!empty($companyGroup)){
				$cGroup['group'] = $companyGroup->memgroup->attributes;
				$cGroup['type'] = $companyGroup->attributes;
				Yii::app()->user->setState('comgroup',$cGroup,1);
			}
		
	/*	$setting      = Yii::app()->filecache->get('setting');
		$displayGroup = $setting['userCenterGroup'] ? $setting['userCenterGroup'] : 0;
		$sql = 'SELECT mg.*,mt.* FROM {{mem_glog}} mg LEFT JOIN {{mem_type}} mt ON mg.itemname=mt.zmt_id WHERE mg.userid='.$record->zm_id.' AND mt.zmg_id IN('.$displayGroup.')';
		$row = Yii::app()->db->createCommand($sql)->queryRow();
		if($row){
			$type = MemType::model()->findByPk($row['zmt_id']);
			$group = MemGroup::model()->findByPk($row['zmg_id']);
			Yii::app()->user->setState('group',$group['attributes'],1);
			Yii::app()->user->setState('level',$type['attributes'],1);
		}*/
	}
	
	//生成激活邮件url
	public function createActivateUrl(){
		$hash = $this->loadModelByfield()->hashEmailParams();
		$url = Yii::app()->urlManager->createUrl('home/user/activateemail',array('hash'=>$hash));
		return Yii::app()->homeUrl.$url;
	}

	//激活邮件url中的参数生成hash函数，顺序为ID#email#code
	public function hashEmailParams(){
		$hash = Yii::app()->securityManager->encrypt($this->zm_id.'#'.$this->zm_email.'#'.$this->zm_code);
		return urlencode($hash);
	}
	
	//激活邮件url中的参数解析函数
	public function getEmailParams(){
		$hash = Yii::app()->request->getParam('hash');
		$hash = urldecode($hash);
		$params = explode('#',Yii::app()->securityManager->decrypt($hash)); 
		//print_r($params);exit;
		$params['zm_id'] = $params[0];
		$params['zm_email'] = $params[1];
		$params['zm_code'] = $params[2];
		return $params;
	}

	//根据单一字段返回用户完整实例，注意字段需为唯一值字段
	public function loadModelByfield($field='zm_name',$value=''){
		$field=$field?$field:'zm_name';
		$value=$value?$value:$this->$field;
		$record = $this->find($field.'=\''.$value.'\'');
		return $record;
	}
	
	//根据用户ID查询指定字段信息,$fields为字段名，逗号隔开，返回ar实例
	public function getFields($id,$fields='zm_name'){
		$criteria=new CDbCriteria;
		$criteria->select=$fields; 
		$criteria->condition='zm_id=:zm_id';
		$criteria->params=array(':zm_id'=>$id);
		$fields=$this->find($criteria); 
		return $fields;
	}
	
	//根据用户username查询指定字段信息,$fields为字段名，逗号隔开，返回ar实例
	public function getFieldsByName($name,$fields){
		$criteria=new CDbCriteria;
		$criteria->select=$fields; 
		$criteria->condition='zm_name=:zm_name';
		$criteria->params=array(':zm_name'=>$name);
		$fields=$this->find($criteria); 
		return $fields;
	}
	
	//获取模型验证失败信息，返回字符串
	public function getErrorsStr(){
		header("Content-type:text/html;charset=utf-8");
		$errors = $this->getErrors();
		$message = '对不起，数据验证失败。信息如下：';
		foreach($errors as $key=>$value){
			$message .= '<br/>'.$key.'：';
			foreach($value as $key1=>$value1){
				$message .= $key1+1;
				$message .= '.'.$value1;		
			}
			return $message;
		}
	}
    /*修改账户余额
     * $id 会员id
     * $val  修改值
     * $type 修改类型  1增加，2减少*/
	public function setMemBalance($id,$val,$type){
		$zm_banlance = self::model()->getFields($id,'zm_balance')->zm_balance;
		if($type=='1'){
			$zm_banlance +=$val;
		}else if($type=='2'){
			if(($zm_banlance-$val)>0){
				$zm_banlance -=$val;
			}else{
				throw new CHttpException(500,'数据出错，没有足够的余额！');
			}			
		}
		self::model()->updateAll(array('zm_balance'=>$zm_banlance),'zm_id=:zm_id',array(':zm_id'=>$id));
	}
	
	/*修改会员积分
     * $id 会员id
     * $val  修改值
     * $type 修改类型  1增加，2减少*/
	public function setMempoint($id,$val,$type){
		$zm_value = self::model()->getFields($id,'zm_value')->zm_value;
		if($type=='1'){
			$zm_value +=$val;
		}else if($type=='2'){
			if(($zm_value-$val)>0){
				$zm_value -=$val;
			}else{
				throw new CHttpException(500,'数据出错，没有足够的积分！');
			}
		}
		self::model()->updateAll(array('zm_value'=>$zm_value),'zm_id=:zm_id',array(':zm_id'=>$id));
	}
	/*
	 * 会员验证状态
	 * */
	public function getCheckStatus($type=null){
		if($type==null){
			return array(
				'1'=>'未验证',
				'2'=>'邮件验证',
				'3'=>'手机验证',
				'4'=>'全部验证'		
			);
		}else{
			$level = $this->getCheckStatus();
			if(array_key_exists($type,$level)){
				return $level[$type];
			}
		}
	}
	
	//异步发送邮件验证码
	public function sendEmailCaptcha(){
		if(Yii::app()->request->isAjaxRequest && !Yii::app()->user->isGuest ){
			$captcha = rand(100000,999999);
			$this->setEmailCaptcha($captcha);
			//发送激活邮件....
			$mailer = Yii::app()->mailer;
			if(Yii::app()->params['mailType'] == 'smtp'){
				$mailer->IsSMTP();
				$mailer->SMTPAuth = true;
			}
			$mailer->AddReplyTo(Yii::app()->user->email);
			$mailer->AddAddress(Yii::app()->user->email);
			$mailer->Subject = F::setting('sitename').'用户操作验证码';
			$params = array('username'=>Yii::app()->user->username,'captcha'=>$captcha);
			$mailer->getView('captcha', array('params'=>$params,'mailer'=>$mailer),'member');
			if($mailer->Send()){
				return true;
			}else{
				return 1;
			}
		} else {
			return -1;
		}
	}
	
	//保存邮件验证码到会话
	function setEmailCaptcha($captcha){
		Yii::app()->user->setState('emailCaptcha',$captcha);
		Yii::app()->user->setState('emailCaptchaDeadline',3600+time());
	}
	
	//验证邮件验证码
	function checkEmailCaptcha($captcha){
		$deadline = Yii::app()->user->getState('emailCaptchaDeadline');
		if($deadline > time()){
			$emailCaptcha = Yii::app()->user->getState('emailCaptcha');
			if($captcha != $emailCaptcha)
				return false;
			Yii::app()->user->setState('emailCaptcha',null);
			return true;
		}
	}
	
	//根据产品id返回用户信息
	function getUserInfoByProductId($id){

	}
	
	//修改邮箱，发送激活邮件，24小时间内缴活成功则修改邮箱
	public function setChangMail($mail){
		//产生随机码
		$captcha = $this->createCode();
		//随机码缓存24小时
		Yii::app()->filecache->set(Company::model()->getCmpUserId().'-mailCacheCode',$captcha,3600*24);
		
		//生成URL
		$hash = Yii::app()->securityManager->encrypt(Company::model()->getCmpUserId().'#'.$mail.'#'.$captcha);
		$url = Yii::app()->urlManager->createUrl('home/user/changemail',array('hash'=>urlencode($hash)));
		
		//发送激活邮件....
		$mailer = Yii::app()->mailer;
		if(Yii::app()->params['mailType'] == 'smtp'){
			$mailer->IsSMTP();
			$mailer->SMTPAuth = true;
		}
		$mailer->AddReplyTo($mail);
		$mailer->AddAddress($mail);
		$mailer->Subject = F::setting('sitename').'用户邮箱验证';
		$params = array('username'=>Company::model()->getCmpUserName(),'url'=>Yii::app()->homeUrl.$url);
		$mailer->getView('changemail', array('params'=>$params,'mailer'=>$mailer),'member');
		if($mailer->Send()){
			return true;
		}else{
			return 1;
		}
	}
	
	/**
	 * 查询后的操作
	 */
	protected function afterFind(){
		foreach($this->level_log as $val){
			$memtype = MemType::model()->findByPk($val->itemname);
			if(!empty($memtype)){
				$this->level[] = $memtype;
				$this->group[] = MemGroup::model()->findByPk($memtype->zmg_id);
			}
		}
		return true;
	}
}